package com.lee.chapter01;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 模拟的程序是，初始的时候，容器是空的，两个线程，一个是消费者，一个是生产者，消费者等到生产者生产了内容后，及时从容器中取出元素然后消费
 */
public class Test_Wait_Notify_Producer_Consumer {
    volatile List<Long> container = new ArrayList<>();

    public void add(Long i) {
        this.container.add(i);
    }

    public int size() {
        return this.container.size();
    }

    public static void main(String[] args) {
        Test_Wait_Notify_Producer_Consumer container = new Test_Wait_Notify_Producer_Consumer();
        Object lock = new Object();

        Thread producer = new Thread(() -> {
            synchronized (lock) {
                while (true) {

                    while (container.size() == 1) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    long l = System.currentTimeMillis();
                    container.container.add(l);
                    System.out.println("我生产了：" + l);
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    lock.notifyAll();
                }
            }
        });

        Thread consumer = new Thread(() -> {
            synchronized (lock) {
                while (true) {
                    while (container.container.size() == 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                    Long aLong = container.container.get(0);
                    container.container.clear();
                    System.out.println("我消费了：" + aLong);
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    lock.notifyAll();
                }
            }
        });

        producer.start();
        consumer.start();


    }


}
